'use strict';
import LeeEvent from './LeeEvent.js';
import { COMPONENTLIFETIMES } from '../constant.js';

class LeeComponent extends LeeEvent {
  static id = 1;
  static Component = Component;

  constructor(options = {}) {
    super();
    const event = LeeEvent.$globalEvent;
    const { lifetimes = {} } = options;

    for (const name of COMPONENTLIFETIMES) {
      if (lifetimes[name] === false) continue;
      const origin = lifetimes[name];
      lifetimes[name] = function(...args) {
        const self = this;
        
        if (name === 'attached' && !self.$componentId) {
          const id = self.$componentId = LeeComponent.id++;
          self.$Event = {};
          for (const name of COMPONENTLIFETIMES) {
            self.$Event[name] = `component_${id}/${name}`;
          }
        }

        const id = self.$componentId;
        if (typeof origin === 'function') {
          origin(this, ...args);
        }
        event.emit(`component_${id}/${name}`, this, ...args);
        event.emit(`component/${name}`, this, ...args);
      };
    }

    options.lifetimes = lifetimes;
    LeeComponent.Component(options);
  }
}

Component = LeeComponent;
